package com.legal.app.service.impl;

import com.legal.app.domain.User;
import com.legal.app.mapper.UserMapper;
import com.legal.common.core.domain.entity.SysRole;
import com.legal.common.core.domain.entity.SysUser;
import com.legal.common.utils.SecurityUtils;
import com.legal.system.service.ISysRoleService;
import com.legal.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author Ale
 * @description 注册时同步注册对应角色若依用户
 * @date 2025/6/23 8:53
 */
@Service
@Transactional // 保证事务一致性
public class UserSyncServiceImpl {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private ISysUserService sysUserService;
    // 若依系统用户服务
    @Autowired
    private ISysRoleService sysRoleService;
    // 角色服务

    /**
     * 小程序用户注册时同步创建若依系统用户
     * @param user 小程序用户对象
     * @return 关联后的user对象
     */
    public User registerWithSysUser(User user) {
        // 1. 先创建若依系统用户
        SysUser sysUser = buildSysUser(user);
        sysUserService.insertUser(sysUser);
        // 插入sys_user表

        // 2. 回填sys_user_id到z_user
        user.setId(sysUser.getUserId());
        userMapper.insert(user);
        // 插入z_user表

        //3. 创建用户角色关联
        SysRole sysRole = sysRoleService.selectRoleById(3L);



        return user;
    }

    /**
     * 构建sys_user对象
     */
    private SysUser buildSysUser(User user) {
        SysUser sysUser = new SysUser();
        sysUser.setUserName(user.getPhoneNumber());
        // 手机号作为登录名
        sysUser.setNickName(user.getNickName() != null ?
                user.getNickName() : user.getPhoneNumber());
        sysUser.setPassword(SecurityUtils.encryptPassword("123456"));
        // 初始密码加密
        sysUser.setStatus(user.getStatus() == 1 ? "1" : "0");
        // 状态同步
        sysUser.setCreateTime(user.getCreateTime());
        // 注册时间同步
        return sysUser;
    }



}
